package com.hontech.desktoppastacooker.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.desktoppastacooker.R

class SwitchSensorView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    private val mTvName: TextView
    private val mTvSw: TextView
    private val mPoint: View

    var isChecked: Boolean? = null

    companion object {
        const val ON = "ON"
        const val OFF = "OFF"
        const val UNKNOWN = "?"
    }

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.view_switch_sensor, this)
        mTvName = view.findViewById(R.id.id_view_tv_name)
        mTvSw = view.findViewById(R.id.id_view_tv_sw)
        mPoint = view.findViewById(R.id.id_view_view_point)

        val attr = context.obtainStyledAttributes(attrs, R.styleable.SwitchSensorView)
        val name = attr.getText(R.styleable.SwitchSensorView_sw_name)
        mTvName.text = name
        attr.recycle()

        mTvSw.text = UNKNOWN
    }

    private fun update(flag: Boolean) {
        if (flag) {
            mPoint.setBackgroundResource(R.drawable.point_red)
            mTvSw.text = ON
        } else {
            mPoint.setBackgroundResource(R.drawable.point_gray)
            mTvSw.text = OFF
        }
    }

    fun set(flag: Boolean) {
        if ((isChecked == null) || (isChecked != flag)) {
            update(flag)
        }
        isChecked = flag
    }
}

